from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import matplotlib.pyplot as plt
import numpy as np
import os
# === 指数平滑函数 ===
def exponential_moving_average(values, alpha=0.3):
    smoothed = []
    for i, val in enumerate(values):
        if i == 0:
            smoothed.append(val)
        else:
            smoothed.append(alpha * val + (1 - alpha) * smoothed[-1])
    return smoothed
# ==== 文件路径 ====
event_file = r"C:\Users\Lenovo\Desktop\000\events.out.tfevents.1755963132.gpu09.87507.0"
output_dir = r"C:\Users\Lenovo\Desktop\000\0.53专家RM"
os.makedirs(output_dir, exist_ok=True)

# ==== 加载事件文件 ====
event_acc = EventAccumulator(event_file)
event_acc.Reload()

# ==== 你要导出的两个指标 ====
tags = {
    'eval/loss': 'Eval Loss',
    'eval/pairwise_accuracy': 'Pairwise Accuracy'
}

# === 绘图 ===
for tag, label in tags.items():
    try:
        data = event_acc.Scalars(tag)
        steps = [x.step for x in data]
        values = [x.value for x in data]

        smoothed_values = exponential_moving_average(values, alpha=0.4)

        # 绘图
        plt.figure(figsize=(8, 5))
        plt.plot(steps, values, color='gray', alpha=0.4, label='Raw Curve')
        plt.plot(steps, smoothed_values, color='black', linewidth=2, label='Smoothed (EMA)')
        plt.xlabel('Evaluation Step', fontsize=12)
        plt.ylabel(label, fontsize=12)
        plt.title(f'{label} Over Time', fontsize=14)
        plt.grid(True)
        plt.legend()
        plt.tight_layout()

        # 保存图像
        filename = tag.replace("/", "_") + "_ema.png"
        save_path = os.path.join(output_dir, filename)
        plt.savefig(save_path, dpi=300)
        print(f"✅ 图已保存：{save_path}")
        plt.close()

    except KeyError:
        print(f"⚠️ 指标不存在：{tag}")